package org.bookie.model.services.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.bookie.model.Category;
import org.bookie.model.services.CategoryDAO;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

/**
 * Hibernate implementation for DAO for {@link Category} instances
 * 
 * @author drobiazko
 *
 */
public class HibernateCategoryDAO extends GenericHibernateDAO<Category, Long> implements CategoryDAO {
	
	private Log log = null;

	/**
	 * {@inheritDoc}
	 */
	public List<Category> getCategories(List<Long> ids) {
		ArrayList<Category> result = new ArrayList<Category>();
		// We could use a criteria query but
		// it do not preserve the order of IDs
		// therefore we need to fetch categories one
		// by one
		for (Iterator iter = ids.iterator(); iter.hasNext();) {
			Long id = (Long) iter.next();
			Category found = findById(id, false);
			if (found != null) {
				result.add(found);
			} else {
				log.warn("User have selected unknown category ID=" + id);
			}
		}
		return result;
	}

	/**
	 * Injector for the log
	 * @category injector
	 * @param log
	 */
	public void setLog(Log log) {
		this.log = log;
	}

	public Category findByName(String name) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		return (Category) crit.add(Restrictions.eq("name", name)).uniqueResult();
	}
}
